package com.example.backend.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.sql.DataSource;
import java.sql.Connection;
import java.time.Instant;
import java.util.HashMap;
import java.util.Map;

/**
 * 系统健康检查控制器
 * 用于诊断后端服务和数据库连接状态
 */
@RestController
public class HealthController {

    @Autowired
    private DataSource dataSource;

    @GetMapping("/api/health")
    public ResponseEntity<Map<String, Object>> health() {
        Map<String, Object> health = new HashMap<>();
        
        try {
            // 基本信息
            health.put("status", "UP");
            health.put("timestamp", Instant.now());
            health.put("service", "ticket-system-backend");
            
            // 数据库连接测试
            try (Connection conn = dataSource.getConnection()) {
                boolean isValid = conn.isValid(5); // 5秒超时测试
                health.put("database", isValid ? "UP" : "DOWN");
                health.put("database_response_time", "< 5s");
            } catch (Exception e) {
                health.put("database", "DOWN");
                health.put("database_error", e.getMessage());
            }
            
            // JVM信息
            Runtime runtime = Runtime.getRuntime();
            Map<String, Object> jvm = new HashMap<>();
            jvm.put("total_memory", runtime.totalMemory() / 1024 / 1024 + "MB");
            jvm.put("free_memory", runtime.freeMemory() / 1024 / 1024 + "MB");
            jvm.put("used_memory", (runtime.totalMemory() - runtime.freeMemory()) / 1024 / 1024 + "MB");
            jvm.put("max_memory", runtime.maxMemory() / 1024 / 1024 + "MB");
            health.put("jvm", jvm);
            
            // 系统信息
            Map<String, Object> system = new HashMap<>();
            system.put("processors", Runtime.getRuntime().availableProcessors());
            system.put("java_version", System.getProperty("java.version"));
            system.put("os", System.getProperty("os.name"));
            health.put("system", system);
            
            return ResponseEntity.ok(health);
            
        } catch (Exception e) {
            health.put("status", "DOWN");
            health.put("error", e.getMessage());
            return ResponseEntity.status(503).body(health);
        }
    }

    @GetMapping("/api/health/simple")
    public ResponseEntity<String> simpleHealth() {
        return ResponseEntity.ok("OK - " + Instant.now());
    }

    @GetMapping("/api/health/database")
    public ResponseEntity<Map<String, Object>> databaseHealth() {
        Map<String, Object> dbHealth = new HashMap<>();
        
        try (Connection conn = dataSource.getConnection()) {
            long startTime = System.currentTimeMillis();
            boolean isValid = conn.isValid(10);
            long responseTime = System.currentTimeMillis() - startTime;
            
            dbHealth.put("status", isValid ? "UP" : "DOWN");
            dbHealth.put("response_time_ms", responseTime);
            dbHealth.put("connection_url", conn.getMetaData().getURL());
            dbHealth.put("driver_name", conn.getMetaData().getDriverName());
            dbHealth.put("timestamp", Instant.now());
            
            return ResponseEntity.ok(dbHealth);
            
        } catch (Exception e) {
            dbHealth.put("status", "DOWN");
            dbHealth.put("error", e.getMessage());
            dbHealth.put("timestamp", Instant.now());
            return ResponseEntity.status(503).body(dbHealth);
        }
    }
}
